﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VSA.Applications.VSA.WebService;

namespace VSA.Applications
{
    public partial class CompanyListForm : Form
    {
        private SearchGuideForm searchForm;
        CompanyInfoForm companyInfoForm;
        DataTable _DataSource = new DataTable();
        string _Sql = string.Empty;
        public CompanyListForm(SearchGuideForm searchForm)
        {
            InitializeComponent();
            this.searchForm = searchForm;
        }

        void GetCompanyListCompleted(object sender, GetCompanyListCompletedEventArgs e)
        {
            gv_CompanyList.DataSource = e.Result.Tables[0];
            
        }

        public CompanyListForm(SearchGuideForm searchForm, DataSet ds, string sql)
        {
            InitializeComponent();
            _Sql = sql;
            gv_CompanyList.DataSource = ds.Tables[0];
            _DataSource = gv_CompanyList.DataSource as DataTable;
            this.searchForm = searchForm;
        }

        private void CompanyListForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            searchForm.Show();
            this.Dispose();
        }

        private void gv_CompanyList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                companyInfoForm = new CompanyInfoForm(this, int.Parse(gv_CompanyList.Rows[e.RowIndex].Cells["CompanyId"].Value.ToString()));
                companyInfoForm.ShowDialog();
                companyInfoForm.TopMost = true;
                this.TopMost = false;
            }
        }

        public void RefreshData()
        {
            MainService _ReCompanyService = WebServiceFactory.GetService();
            _ReCompanyService.GetCompanyListCompleted += new GetCompanyListCompletedEventHandler(GetCompanyListCompleted);
            _ReCompanyService.GetCompanyListAsync(_Sql);
        }

        private void btn_Export_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = "xls";
            saveFileDialog.Filter = "Excel file|*.xls";
            saveFileDialog.FileName = "Sheet1";
            saveFileDialog.AddExtension = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    new ExcelFile(_DataSource).Create(saveFileDialog.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error occur when open file, it might be opened！\n" + ex.Message);
                }

            }

        }
    }
}
